/*
 * @Description: 
 * @version: 
 * @Author: CoderXZ
 * @Date: 2020-06-10 10:40:39
 * @LastEditors: CoderXZ
 * @LastEditTime: 2020-06-28 22:30:41
 */

import { wx } from "./Wx";


const { ccclass, property } = cc._decorator;

@ccclass
export default class Utils {

    // 上传微信子域排行数据,可直接在主域中使用.
    public static updateUserData(key: string, data: any): Promise<any> {
        if (!this.isWechat()) {
            return Promise.resolve();
        }
        if (!key || !data) {
            return;
        }
        return new Promise<any>((resolve, reject) => {

            let timestamp = new Date().getTime();

            let saveData = {
                "wxgame": {
                    "score": data.heroNum,
                    "update_time": timestamp
                },
                "heroTotalLv": data.heroTotalLv
            }

            wx.setUserCloudStorage({
                KVDataList: [{
                    key: key,
                    value: JSON.stringify(saveData)
                }],
                success: function (args) {
                    console.log("上传排行榜成功.", args);
                    wx.showToast({
                        title: '上传成功',
                    });

                    setTimeout(function () {
                        wx.hideToast();
                    }, 1500)
                    resolve(args);
                },
                fail: function (args) {
                    console.log("上传排行榜失败.", args);
                    reject(args);
                }
            })
        })
    }

    public static isWechat(): boolean {
        return cc.sys.platform === cc.sys.WECHAT_GAME;
    }

    public static clearUserCloudStorage(keys: string[]) {
        if (this.isWechat()) {
            wx.removeUserCloudStorage({
                keyList: keys || [],
                success(res) {
                    console.warn("已成功清除微信托管数据", res);
                }
            })
        }
    }

    public static sendMessageToSub(operation: string, params: any) {
        if (!this.isWechat()) {
            return;
        }
        let openDataContext = wx.getOpenDataContext();
        if (openDataContext) {
            let data: any = {};
            data.what = operation;
            data.arguments = params;
            openDataContext.postMessage(data);
        }
    }

}
